package cn.jimmie.learn.viewArt.refreshview.core.scrollview;

import android.view.View;

import cn.jimmie.learn.viewArt.refreshview.core.ContentView;
import cn.jimmie.learn.viewArt.refreshview.core.RefreshState;

/**
 * function :
 *
 * <p> Create Time:  2019年04月15日 09:44 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class ScrollContentView implements ContentView, RefreshScrollView.OnOverScrollListener {
    private static final int MIN_TIME_OFFSET = 300;
    private static final int SCROLL_TOP = 0x11;
    private static final int SCROLL_OTHER = 0x33;

    private int mScrollState = SCROLL_TOP;


    private RefreshScrollView mView;
    private OnFootLocationListener mListener;
    private RefreshState mStatus;
    private boolean isFooterAdded;


    public ScrollContentView(View view, RefreshState status) {
        this.mView = (RefreshScrollView) view;
        this.mView.setOverScrollListener(this);
        this.mStatus = status;
    }

    @Override
    public boolean isTopPosition() {
        // mView 不可见, 则可以触发刷新
        if (mView.getVisibility() != View.VISIBLE) {
            return true;
        }
        return mScrollState == SCROLL_TOP;
    }

    @Override
    public void setFooterVisibility(View view, int visible) {
        if (!mStatus.isFootViewEnable()) return;

        if (!isFooterAdded) {
            mView.setFootView(view);
            isFooterAdded = true;
        }
        view.setVisibility(visible);
    }

    @Override
    public void setOnFooterLocationListener(OnFootLocationListener listener) {
        this.mListener = listener;
    }

    @Override
    public void release() {

    }

    @Override
    public void removeFootView(View v) {
        if (isFooterAdded) {
            mView.removeFootView();
        }
    }

    private long avoidMulti;

    @Override
    public void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        if (!mStatus.isFootViewEnable()) return;

        if (scrollY == 0) mScrollState = SCROLL_TOP;
        else mScrollState = SCROLL_OTHER;

        if (!clampedY) return;
        long cur = System.currentTimeMillis();
        if (cur - avoidMulti < MIN_TIME_OFFSET) {
            return;
        }

        // 1. 没有到底,返回
        // 2. 刷新状态不为 IDLE,返回
        // 3. 刷新返回为 END,返回
        // 4. 不满一屏,返回
        if (scrollY <= 0 ||
                mStatus.getLoadState() != RefreshState.LoadState.IDLE ||
                mStatus.getResultState() == RefreshState.ResultState.END
        ) return;

        mStatus.setLoadState(RefreshState.LoadState.PULLING);
        if (mListener != null) mListener.onFooterRefresh();
        avoidMulti = cur;
    }
}
